import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
	state:{
		token:getToken(),
		username:sessionStorage.getItem('username') || '',
		isFirstLogin:null,
		permissions:[]
	},
	mutations:{
		SET_TOKEN: (state,token) => {
			state.token = token
		},
		SET_USERNAME: (state,name) => {
			state.username = name;
			sessionStorage.setItem('username',name);
		},
		SET_ISFIRSTLOGIN: (state,flag) => {
			state.isFirstLogin = flag;
		},
		SET_PERMISSIONS: (state,permissionArr) => {
			state.permissions = permissionArr
		}
	},
	actions:{

		// 用户登录
		LoginByUsername({ commit },userInfo) {
			return new Promise((resolve,reject) => {
				loginByUsername(userInfo).then(response => {
					if (response && response.code == 0) {	//登录成功
						commit('SET_TOKEN',response.token)
						commit('SET_USERNAME',response.username)
						setToken(response.token)
						// 设置是否是第一次登录标识
						if(response.isFirstLogin){
							commit('SET_ISFIRSTLOGIN',response.isFirstLogin);
						}
					}
					resolve(response);
				}).catch(error => {
					reject(error)
				})

			})
		},

		// 获取用户信息


		// 登出
		LogOut({commit}) {
			return new Promise((resolve,reject) => {
				logout().then(response => {
					let result = response;
					if(result.code == 0){
						commit('SET_TOKEN','')
						commit('SET_PERMISSIONS',[])
						removeToken()
					}
					resolve(result)
				}).catch(error => {
					commit('SET_TOKEN','')
					commit('SET_PERMISSIONS',[])
					removeToken()
					location.reload();
					reject(error)
				})
				
			})
		},

		// 设置用户权限permission
		setPermissions({commit},permissionArr) {
			return new Promise((resolve) => {
				commit('SET_PERMISSIONS',permissionArr);
				resolve()
			})
		}
	}
}

export default user